package supershop.controller;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import supershop.dao.IProductDao;
import supershop.dto.ProductDTO;
import supershop.model.Product;

@Controller
@RequestMapping("/admin/start/product")
public class ProductController {

	@Resource
	private IProductDao productDao;
	
	@RequestMapping("/findAll.do")
	@ResponseBody
	public Map findAll(ProductDTO dto) {
		List<Product> list = productDao.findAll(dto);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "查询成功");
		map.put("count", productDao.getCount(dto));
		map.put("data", list);
		return map;
	}
	
	//添加或修改
	@RequestMapping("/addOrEdit.do")
	@ResponseBody
	public int addOrEdit(Product p) {
		if(p.getId()==null) {
			return productDao.add(p);
		}else {
			return productDao.edit(p);
		}
	}
	
	//上下架
	@RequestMapping("/putOn.do")
	@ResponseBody
	public int putOn(int id,String isPutOnSale) {
		return productDao.isPutOn(id, isPutOnSale);
	}
	
	//推荐/取消推荐
	@RequestMapping("/recommend.do")
	@ResponseBody
	public int recommend(int id,String isToday) {
		return productDao.recommend(id, isToday);
	}
	
	
	//上传图片
	@RequestMapping("/upload.do")
	@ResponseBody
	public Map upload(MultipartFile file) {
		//获取文件原始名
		String name = file.getOriginalFilename();
		System.out.println(name); 
		String path = "d:\\upload\\"+name;
		try {
			file.transferTo(new File(path));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "");
		map.put("data",name);
		return map;
	}
	
	//修改图片路径
	@RequestMapping("/updateUrl.do")
	@ResponseBody
	public int updateUrl(int id,String url) {
		return productDao.updateUrl(id, url);
	}
	
}
